<script lang="ts" setup>
import { useTemplateRef, ref, provide, toRef, onActivated, onDeactivated, onUnmounted } from 'vue'
import { navBarHeightKey } from './symbol-key.ts'
import { useResizeObserver, useDebounceFn } from '@vueuse/core'
import { ScrollTrigger } from 'gsap/ScrollTrigger'
import { useScrollGroup } from '@/hooks/reno14-pro.ts'
import NavBar from './second-navbar/index.vue'
import Block1 from './block/1/index.vue'
import Block2 from './block/2/index.vue'
import Block3 from './block/3/index.vue'
import Block4 from './block/4/index.vue'
import Block5 from './block/5/index.vue'
import Block6 from './block/6/index.vue'
import Tips from './block/tips/index.vue'

const navBarRef = useTemplateRef<HTMLDivElement | null>('navBarRef')
const _navBarHeight = ref(0)
provide(
  navBarHeightKey,
  toRef(() => _navBarHeight.value),
)

const { key: groupKey, value: groupValue } = useScrollGroup()
const reno14ProRef = useTemplateRef<HTMLDivElement | null>('reno14ProRef')
let reno14LastHeight = 0
const scrollRefresh = useDebounceFn(() => {
  if (navBarRef.value) {
    _navBarHeight.value = navBarRef.value.offsetHeight
  }

  ScrollTrigger.getAll().forEach((scrollInstance) => {
    if ((scrollInstance.vars as Record<string, unknown>)?.[groupKey] === groupValue) {
      scrollInstance.refresh()
    }
  })
}, 500)
let stopObserver: (() => void) | null = null

onActivated(() => {
  const observer = useResizeObserver(reno14ProRef, (entries) => {
    const currentHeight = Math.floor(entries[0].contentRect.height)
    if (Math.abs(currentHeight - reno14LastHeight) >= 2) {
      reno14LastHeight = currentHeight
      scrollRefresh()
    }
  })
  stopObserver = observer.stop
})
onDeactivated(() => {
  if (stopObserver) {
    stopObserver()
    stopObserver = null
  }
})
onUnmounted(() => {
  if (stopObserver) {
    stopObserver()
    stopObserver = null
  }
})
</script>

<template>
  <div ref="reno14ProRef">
    <div ref="navBarRef" class="sticky top-0 z-99">
      <nav-bar />
    </div>
    <Block1 />
    <Block2 />
    <Block3 />
    <Block4 />
    <Block5 />
    <Block6 />
    <Tips />
  </div>
</template>
